package com.cl.mypureframe.activity;

import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.cl.mypureframe.R;
import com.cl.mypureframe.dialog.MProgressDialog;
import com.cl.mypureframe.widget.ViewTitle;

import java.util.concurrent.atomic.AtomicBoolean;


/**
 * MyWebviewActivity
 * Created by Lei on 2018/5/10.
 */
public class MyWebviewActivity extends BaseActivity {
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_URL = "url";
    public static final String EXTRA_TITLEBAR = "titlebar";
    private WebView wv;
    private MProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initContenViewAndBack(R.layout.activity_mywebview, R.string.app_name);
        View ivLeft = viewTitle.activateView(ViewTitle.TitleType.BACK);
        ivLeft.setOnClickListener(view -> onBackPressed());

        wv = findViewById(R.id.wv_main);

        String title = getIntent().getStringExtra(EXTRA_TITLE);
        String url = getIntent().getStringExtra(EXTRA_URL);
        boolean isTitlebar = getIntent().getBooleanExtra(EXTRA_TITLEBAR, true);
        viewTitle.setVisibility(isTitlebar ? View.VISIBLE : View.GONE);
        if (title != null) {
            setTitleName(title);
        }

        if (url != null) {
            initWebViewAll(wv, url);

            progressDialog = new MProgressDialog(this);
            progressDialog.show();
            wv.setWebChromeClient(new WebChromeClient() {
                final AtomicBoolean mIsLoadFinish = new AtomicBoolean(false);

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    super.onProgressChanged(view, newProgress);
                    if (newProgress == 100) {
                        if (mIsLoadFinish.compareAndSet(false, true)) {
                            progressDialog.dismiss();
                        }
                    }
                }
            });

        }
    }

    @Override
    public void onBackPressed() {
        if (wv.canGoBack()) {
            wv.goBack();
        } else {
            super.onBackPressed();
        }
    }

}